import validate from 'wechat-validate'

Page({
  // 注入插件validate
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: ''
  },

  // 校验规则
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-9]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    code: [
      { required: true, message: '请填写短信验证码!' },
      { pattern: /^\d{6}$/, message: '验证码为6位数字' }
    ]
  },

  // 获取验证码
  async getSMSCode() {
      // 校验手机号
      // 单独只验证 mobile 这个数据
      const data = this.validate('mobile')
      // console.log(data);
      if (!data.valid) return wx.utils.toast(data.message)
  
      // else do something
    this.setData({
      countDownVisible: true
    })
    
    // 发送请求获取验证码
    const res = await wx.http.get("/code",{
      mobile: this.data.mobile
    })
    console.log(res);
    
  },
  // 倒计时变化时
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },

  // 登录表单提交
  async onSubmit() {
    const {mobile, code} = this.data
    const isOk = this.validate() 
    // 验证通过发送请求
    if(isOk){
      const res = await wx.http.post("/login",{
        mobile,
        code
      })
      const app = getApp()
      app.token = res.data.token
      wx.setStorageSync('token',res.data.token)
      wx.utils.toast('登录成功')

    }
    
    
  }
})
